package com.chainyoung.trademarket.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.bus.AppManagerEvent;
import com.chainyoung.common.bus.RxBus;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.di.DaggerAppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.integration.AppManager;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.ClearEditText;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.chainyoung.trademarket.R;
import com.chainyoung.trademarket.base.MyApplication;
import com.chainyoung.trademarket.di.component.DaggerLoginComponent;
import com.chainyoung.trademarket.di.module.LoginModule;
import com.chainyoung.trademarket.mvp.contract.LoginContract;
import com.chainyoung.trademarket.mvp.presenter.LoginPresenter;

import org.simple.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.chainyoung.common.bus.AppManagerEvent.APP_EXIT;

@Route(path = RouterConstants.PATH_MAIN_LOGIN)
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {


    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.et_account)
    ClearEditText etAccount;
    @BindView(R.id.et_pwd)
    ClearEditText etPwd;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.cb_protocol)
    CheckBox cbProtocol;
    @BindView(R.id.tv_remind_info)
    TextView tvRemindInfo;

    private String accountNo;
    private String pwd;
    private boolean isAgreed;

    public static final String FROM_EMAIL = "isFromEmail";

    private boolean isFromOtherApp;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerLoginComponent.builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        isFromOtherApp=getIntent().getBooleanExtra(LibConstant.FROM_OTHER_APP,false);
    }



    @Override
    protected void initUI() {

        isFromOtherApp = getIntent().getBooleanExtra(LibConstant.FROM_OTHER_APP, false);
        etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvRemindInfo.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {
                accountNo = s.toString();
                checkCanSubmit();
            }
        });

        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvRemindInfo.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {
                pwd = s.toString();
                checkCanSubmit();
            }
        });

        cbProtocol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgreed = isChecked;
            }
        });
        String account = SPUtil.getString(LibConstant.ACCOUNT);
        if (!TextUtils.isEmpty(account)) {
            etAccount.setText(account);
            etAccount.setSelection(account.length());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void initData() {

    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }


    @OnClick({R.id.btn_login, R.id.tv_forget_pwd, R.id.tv_register, R.id.tv_user_protocol})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                //launch(MainActivity.class);
                /*if (!isAgreed) {
                    ToastUtil.showToast("请同意用户协议");
                    return;
                }*/
                if (!StringUtil.isMobileNumber(StringUtil.viewGetText(etAccount))&&!StringUtil.isEmail(StringUtil.viewGetText(etAccount))){
                    tvRemindInfo.setText("账号或密码输入错误");
                    return;
                }

                TreeMap<String, Object> map = new TreeMap<>();
                map.put("username", accountNo);
                map.put("password", pwd);
                mPresenter.getLogin(map);
                break;
            case R.id.tv_forget_pwd:
                launch(ForgetPwdActivity.class);
                break;
            case R.id.tv_register:
                Bundle bundle = new Bundle();
                bundle.putBoolean(FROM_EMAIL, false);
                launch(RegisterActivity.class, bundle);
                break;
            case R.id.tv_user_protocol:
                break;
        }
    }

    private void checkCanSubmit() {
        accountNo = etAccount.getText().toString().trim();
        pwd = etPwd.getText().toString().trim();
        if (TextUtils.isEmpty(accountNo) || TextUtils.isEmpty(pwd)) {
            btnLogin.setEnabled(false);
        } else {
            btnLogin.setEnabled(true);
        }
    }


    @Override
    public void onLoginSuccess(UserInfo userInfo) {
        EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.LOGIN_IN, userInfo));
        if (isFromOtherApp) {
            RouterUtils.getInstance()
                    .build(RouterConstants.PATH_MAKE_CASH)
                    .withBoolean(LibConstant.FROM_OTHER_APP,true)
                    .navigation(mContext);
        } else {
            launch(MainMarketActivity.class);
        }
        finish();
    }


    @Override
    public void onBackPressed() {
        exitBy2Click();
    }


    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit;
        if (!isExit) {
            isExit = true; // 准备退出
            ToastUtil.showToast(getString(R.string.press_again_and_exit));
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            RxBus.getDefault().post(new AppManagerEvent(APP_EXIT, getString(R.string.exit_app)));
        }
    }

}
